package com.systemic.service.impl;

import com.systemic.dto.SubjectDto;
import com.systemic.mapper.*;
import com.systemic.pojo.*;
import com.systemic.service.DraftService;
import com.systemic.utils.FileUtils;
import com.systemic.vo.DraftInfoVo;
import com.systemic.vo.DraftVo;
import com.systemic.vo.ImageInfoVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: DraftServiceImpl
 * @Description:
 * @Author:
 * @CreateTime: 2024-01-05 13:56
 * @Version:
 **/
@Service
public class DraftServiceImpl implements DraftService {

    private final Integer status = 2; // 状态值2 表示草稿，用来执行查询
    private final Integer dynamic_status = 1;  // 状态值1 表示动态，用来执行查询

    @Resource
    private DraftMapper draftMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private DynamicImageMapper dynamicImageMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private SubjectDynamicMapper subjectDynamicMapper;

    @Value("${image.diUrl}")
    private String diUrl;
    @Value("${image.dynamicImage}")
    private String dynamicImagePath;        // 使用注解的方式定义文件地址

    /**
     * 暂存草稿: 只有发布动态的环节，用户可以选择暂存草稿
     * @param images
     * @param draft
     * @param subject
     * @return
     */
    @Override
    @Transactional
    public int staging(MultipartFile[] images, Draft draft, Integer[] subject) {
        int row = 0;
        // 第一层判断：非空
        if (draft!=null) {
            Date date = new Date();
            try{
                draft.setGmtCreate(date);
                draft.setGmtModified(date);
                row = draftMapper.insert(draft);
            } catch(Exception e) {
                throw new RuntimeException("新增dynamic错误" + e);
            }
            // 添加图片
            Integer id = draftMapper.getLastInsertId();   // 获取新增动态时数据表自增的主键
            int result = 0;
            if (images!=null){
                for (MultipartFile image : images) {
                    try{
                        String url = FileUtils.uploadImage(image, dynamicImagePath, diUrl);
                        DynamicImage dynamicImage = new DynamicImage();
                        dynamicImage.setDid(id);    // 将动态主键设为该表的did属性
                        dynamicImage.setImage(url);  // 获取图片url
                        dynamicImage.setStatus(2);
                        row = dynamicImageMapper.insert(dynamicImage) + row;
                    } catch (Exception e) {
                        throw new RuntimeException("上传失败" + e);
                    }
                    result++; // 假设每次上传成功增加计数器
                }
            }
            System.out.println("上传图片数量："+ result);

            // TODO: 新增话题业务
            if (subject!=null){
                // 把话题id和动态id存储在关系表中
                for (Integer sid:subject) {
                    SubjectDynamic subjectDynamic = new SubjectDynamic();
                    subjectDynamic.setSid(sid); // 写入当前话题id
                    subjectDynamic.setDid(id);  // 写入当前草稿id
                    subjectDynamic.setStatus(status);  //写入当前状态值
                    row = subjectDynamicMapper.insert(subjectDynamic) + row;
                }
            }

        }
        return row;
    }

    /**
     * 获取用户的草稿箱列表
     * @param uid
     * @return
     */
    @Override
    public List<DraftVo> selectListByUid(Integer uid) {
        // 根据前端传来的uid查询该用户的所有草稿
        List<Draft> drafts = draftMapper.selectListByUid(uid);
        List<DraftVo> draftVoList = new ArrayList<>();
        for (Draft draft:drafts) {
            DraftVo draftVo = new DraftVo();
            try{
                Integer id = draft.getId();

                draftVo.setId(id);
                draftVo.setUid(draft.getUid());
                draftVo.setContent(draft.getContent());
                draftVo.setCategory(draft.getCategory());
                draftVo.setGmtCreate(draft.getGmtCreate());
                DynamicImage dynamicImage = dynamicImageMapper.selectByDid(id, status);
                if (dynamicImage!=null){
                    draftVo.setImage(dynamicImage.getImage());
                }
                draftVoList.add(draftVo);
            }catch(Exception e){
                throw new RuntimeException("错误"+e);
            }
        }
        return draftVoList;
    }


    /**
     * 获取草稿具体信息
     * @param id
     * @return
     */
    @Override
    public DraftInfoVo selectById(Integer id) {
        Draft draft = draftMapper.selectById(id);
        DraftInfoVo draftInfoVo = new DraftInfoVo();
        List<ImageInfoVo> imageInfoVos = new ArrayList<>();
        if (draft!=null){
            Integer did = draft.getId(); //草稿id
            List<DynamicImage> dynamicImageList = dynamicImageMapper.selectListByDid(id, status);
            for (DynamicImage dynamic:dynamicImageList) {
                ImageInfoVo imageInfoVo = new ImageInfoVo();
                try{
                    imageInfoVo.setId(dynamic.getId());
                    imageInfoVo.setDid(dynamic.getDid());
                    imageInfoVo.setImage(dynamic.getImage());
                    imageInfoVo.setStatus(dynamic.getStatus());
                    imageInfoVos.add(imageInfoVo);
                }catch(Exception e){
                    throw new RuntimeException("错误" + e);
                }
            }
            // 初始化
            List<SubjectDto> subjects = new ArrayList<>();
            SubjectDynamic subjectDynamic = new SubjectDynamic();
            // 根据草稿id查询关联的话题
            subjectDynamic.setDid(did);
            subjectDynamic.setStatus(status);
            List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
            if (!subjectDynamics.isEmpty()){
                for (SubjectDynamic sub:subjectDynamics) {
                    //使用话题id（sid）做查询，再把sid和sname写入SubjectDto实体类
                    Subject subject = subjectMapper.selectById(sub.getSid());
                    if (subject!=null){
                        SubjectDto subjectDto = new SubjectDto();
                        subjectDto.setId(subject.getId());
                        subjectDto.setSname(subject.getSname());
                        subjects.add(subjectDto);
                    }
                }
            }
            // 判断是否为空
            if (!subjects.isEmpty()){
                draftInfoVo.setSubjects(subjects);
            }

            draftInfoVo.setId(draft.getId());
            draftInfoVo.setUid(draft.getUid());
            draftInfoVo.setContent(draft.getContent());
            draftInfoVo.setCategory(draft.getCategory());
            draftInfoVo.setGmtCreate(draft.getGmtCreate());
            draftInfoVo.setImages(imageInfoVos);
        }
        return draftInfoVo;
    }

    /**
     * 删除草稿
     * @param draft
     * @return
     */
    @Override
    @Transactional
    public int delete(Draft draft) {
        int row = 0;
        DynamicImage dynamicImage = new DynamicImage();
        Integer did = draft.getId();
        try{
            dynamicImage.setDid(did);
            dynamicImage.setStatus(status);
            // TODO: 根据 dynamicImage的信息查询本地待删除的图片
            List<DynamicImage> dynamicImageList = dynamicImageMapper.selectList(dynamicImage);
            if (dynamicImageList!=null){
                for (DynamicImage image:dynamicImageList) {
                    // url转换对应的本地路径
                    URL url = new URL(image.getImage());
                    String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                    if (FileUtils.delete(dynamicImagePath + fileName)){
                        // 删除草稿关联的图片数据记录
                        dynamicImageMapper.deleteById(image.getId());
                    }else{
                        System.out.println("文件不存在");
                    }
                }
            }
        }catch(Exception e){
            throw new RuntimeException("错误" + e);
        }
        // TODO:删除关联话题
        // 先根据did和status查询有哪些话题，使用List接收
        SubjectDynamic subjectDynamic = new SubjectDynamic();
        subjectDynamic.setDid(did);
        subjectDynamic.setStatus(status);
        List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
        // 对list遍历，每次执行删除操作
        for (SubjectDynamic sub:subjectDynamics) {
            row = subjectDynamicMapper.delete(sub) + row;
        }
        row = draftMapper.delete(draft) + row;
        if (row==0){
            throw new RuntimeException("删除草稿失败");
        }
        return row;
    }

    /**
     * 更新草稿
     * @param images
     * @param draft
     * @param subject
     * @return
     */
    @Override
    @Transactional
    public int update(MultipartFile[] images, Draft draft, Integer[] subject) {
        int row = 0;
        int result = 0;
        DynamicImage dynamicImage = new DynamicImage();
        if (draft!=null){
            Integer did = draft.getId();
            // step1.清除旧关联
            try{
                dynamicImage.setDid(did);
                dynamicImage.setStatus(status);
                List<DynamicImage> dynamicImageList = dynamicImageMapper.selectList(dynamicImage);
                if (!dynamicImageList.isEmpty()){
                    for (DynamicImage image:dynamicImageList) {
                        // url转换对应的本地路径
                        URL url = new URL(image.getImage());
                        String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                        if (FileUtils.delete(dynamicImagePath + fileName)){
                            dynamicImageMapper.deleteById(image.getId());
                            System.out.println("删除成功");
                        }else{
                            System.out.println("文件不存在");
                        }
                    }
                }
                // 先根据did和status查询有哪些话题，使用List接收
                SubjectDynamic subjectDynamic = new SubjectDynamic();
                subjectDynamic.setDid(did);
                subjectDynamic.setStatus(status);
                List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
                // 对list遍历，每次执行删除操作
                if (!subjectDynamics.isEmpty()){
                    for (SubjectDynamic sub:subjectDynamics) {
                        row = subjectDynamicMapper.delete(sub) + row;
                    }
                }
            }catch(Exception e){
                throw new RuntimeException("错误" + e);
            }
            // step2.更新
            if (images!=null){
                // 将文件上传本地
                for (MultipartFile image : images) {
                    try{
                        String url = FileUtils.uploadImage(image, dynamicImagePath, diUrl);
                        DynamicImage dynamicImg = new DynamicImage();
                        dynamicImg.setDid(did);
                        dynamicImg.setImage(url);  // 获取图片url
                        dynamicImg.setStatus(status);
                        row = dynamicImageMapper.insert(dynamicImg) + row;
                    } catch (Exception e) {
                        throw new RuntimeException("上传失败" + e);
                    }
                    result++; // 假设每次上传成功增加计数器
                }
                System.out.println("上传图片数量："+ result);
            }

            if (subject!=null){
                // 把话题id和动态id存储在关系表中
                for (Integer sid:subject) {
                    SubjectDynamic subjectDynamic = new SubjectDynamic();
                    subjectDynamic.setSid(sid); // 写入当前话题id
                    subjectDynamic.setDid(did);  // 写入当前草稿id
                    subjectDynamic.setStatus(status);  //写入当前状态值
                    row = subjectDynamicMapper.insert(subjectDynamic) + row;
                }
            }
            // 更新数据库记录
            draft.setGmtModified(new Date());
            row = draftMapper.update(draft) + row;
        }
        return row;
    }

    /**
     * 草稿转动态
     * 1.根据前端传来的id查询指定草稿信息
     * 2.把草稿信息映射在动态实体类
     * 3.执行新增动态操作，如果影响行数不为0 获取自增的动态主键 并且 执行删除草稿操作，否则报错
     * 4.根据前端传递的草稿id查询关联的图片，如果查询结果不为空，做修改操作，把did修改为 获取自增的动态主键，把status修改为1
     * @param draft
     * @return
     */
    @Override
    @Transactional
    public int push(Draft draft) {
        int row = 0;
        Integer draftId = draft.getId();
        // 根据前端传来的id查询指定草稿信息
        Draft draftInfo = draftMapper.selectById(draftId);
        Dynamic dynamic = new Dynamic();
        // 把草稿信息映射在动态实体类
        Date date = new Date();
        dynamic.setUid(draftInfo.getUid());
        dynamic.setContent(draftInfo.getContent());
        dynamic.setGmtCreate(date);
        dynamic.setGmtModified(date);
        row = dynamicMapper.insert(dynamic);
        if (row==0){
            throw new RuntimeException("新增动态失败");
        }
        // 获取自增的动态主键
        Integer dynamicId = dynamicMapper.getLastInsertId();
        // 根据前端传递的草稿id查询关联的图片
        List<DynamicImage> dynamicImages = dynamicImageMapper.selectListByDid(draftId,status);
        // 如果查询结果不为空，做修改操作
        if (!dynamicImages.isEmpty()){
        //使用foreach，在每轮执行更新操作：把did修改为 动态主键，把status修改为1
            for (DynamicImage image:dynamicImages) {
                image.setDid(dynamicId);
                image.setStatus(1);
                try{
                    dynamicImageMapper.update(image);
                }catch(Exception e){
                    throw new RuntimeException("错误" + e);
                }
            }
        }

        // TODO: 对话题关系表做修改
        SubjectDynamic subjectDynamic = new SubjectDynamic();
        subjectDynamic.setDid(draftId);
        subjectDynamic.setStatus(status);
        List<SubjectDynamic> subjectDynamicList = subjectDynamicMapper.select(subjectDynamic);
        if (!subjectDynamicList.isEmpty()){
            // 遍历查询结果，写入必要的更新条件：id、did、status
            for (SubjectDynamic sudList:subjectDynamicList) {
                SubjectDynamic sub = new SubjectDynamic();
                sub.setId(sudList.getId());
                sub.setDid(dynamicId);  // 将更新后的动态id写入
                sub.setStatus(dynamic_status);   // 状态值1，表示为动态
                row = subjectDynamicMapper.update(sub) + row;
            }
        }
        row = draftMapper.delete(draft) + row;
        return row;
    }






}
